package net.openadventure.animation;

import net.openadventure.State;
import net.openadventure.sprites.Sprite;
import util.Point;

public class OneTimeMove extends Animation {

	protected String spriteName;
	protected int speed; // TODO make this pixels per update (double)
	protected int fromX;
	protected int fromY;
	protected int toX;
	protected int toY;

	public OneTimeMove(String spriteName, int speed, int fromX, int fromY,
			int toX, int toY) {
		this.spriteName = spriteName;
		this.speed = speed;
		this.fromX = fromX;
		this.fromY = fromY;
		this.toX = toX;
		this.toY = toY;
	}

	@Override
	public void updateSprite(State state) {
		Sprite target = state.getSprites().get(spriteName);

		int xMove = 0;
		int yMove = 0;

		if (target != null) {

			Point actualCenter = target.getActualCenter();

			if (actualCenter.getX() != toX) {
				if (Math.abs(toX - actualCenter.getX()) < speed) {
					xMove = toX - actualCenter.getX();
				} else {
					xMove = speed
							* (int) Math.signum(toX - actualCenter.getX());
				}
			}
			if (actualCenter.getY() != toY) {
				if (Math.abs(toY - actualCenter.getY()) < speed) {
					yMove = toY - actualCenter.getY();
				} else {
					yMove = speed
							* (int) Math.signum(toY - actualCenter.getY());
				}
			}

			state.getSprites().put(
					spriteName,
					new Sprite(target.getImagePath(), target.getX() + xMove,
							target.getY() + yMove, target.getOriginalCenter(),
							target.getOriginalFootPrint(), target.getWidth(),
							target.getHeight(), target.getFlipHorizontal(),
							target.getFlipVertical()));
		}

	}

	@Override
	public boolean finished(State state) {
		Sprite target = state.getSprites().get(spriteName);

		if (target != null) {
			Point actualCenter = target.getActualCenter();
			return toX == actualCenter.getX() && toY == actualCenter.getY();
		} else {
			return true;
		}
	}
}
